<template>
    <div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <div class="container">
            <h4 style="margin-bottom: 20px">{{manufacture.breedName}}</h4>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="批次：">
                        {{manufacture.batch}}
                    </el-form-item>
                    <el-form-item label="入库类型：">
                        {{manufacture.type}}入库
                    </el-form-item>
                    <el-form-item label="状态：">
                        {{manufacture.isCheck == 0?'未检测':'已检测'}}
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="入库时间：">
                        {{manufacture.time}}
                    </el-form-item>
                    <el-form-item label="数量：" v-if="keli">
                        {{manufacture.totalNum}}{{manufacture.units}}
                    </el-form-item>
					<el-form-item label="数量：" v-else>
					    {{manufacture.surplusNum}}{{manufacture.units}}
					</el-form-item>
					<el-form-item label="上次报告日期：">
					    {{time || ''}}
					</el-form-item>
                </el-col>
            </el-row>
        </div>
        <div v-show="showForm == 2">
            <div class="container" style="margin-top:20px">
                <h3 style="margin-bottom: 20px">检测</h3>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="检测机构：">
                            {{ruleForm.organization}}
                        </el-form-item>
                       <div v-if='switchHeadTab =="生产系统"'>
                           <el-form-item label="* 标准类型：" prop="standard" v-if="this.storname !='中药材' && this.storname != '辅料'">
                               {{standards}}
                           </el-form-item>
                       </div>
                        <el-form-item label="提取饮片执行标准：" v-if="storname == '提取饮片'">
                            {{ruleForm.standard}}
                        </el-form-item>
                        <el-form-item label="中药配方颗粒执行标准：" v-if="storname == '配方颗粒'">
                            {{ruleForm.standard}}
                        </el-form-item>
                        <el-form-item label="检测结果：">
                            {{ruleForm.detectionResult == 1?'合格':'不合格'}}
                        </el-form-item>
                        <el-form-item label="检测报告：" v-if='storname !== "配方颗粒" ||(storname == "配方颗粒" && standards == "国标")'  style="width:500px">
                            <span v-for="item in sceneUrls" :key="item.id">
                                <img v-if="item.hz == 'pdf'" src="./编组.png" width="150" height="150" style="margin-left:10px;"/>
								<img v-else :src="item.url" width="150" height="150" style="margin-left:10px;"/>
                            </span>
							<!-- <upload-img ref="uploadChang"  :files='sceneUrls'></upload-img> -->
                            <!-- <upload-file ref="upload" :files='sceneUrls' :isFalse="true"></upload-file> -->
                        </el-form-item>
                        <el-form-item v-if='standards == "省标" && storname == "配方颗粒"' label="检测报告：" style="width:500px">
                            <div v-for="item in sceneUrls" :key="item.id">
                                <div class='image-list'>
                                    <span class="location">地区：{{item.address}}</span>
                                    <img v-if="item.hz == 'pdf'" src="./编组.png" width="150" height="150" style="margin-left:10px;"/>
								    <img class='item' v-else v-for='jack in item.imageList' :src="jack.url" width="150" height="150" style="margin-left:10px;"/>
                                </div>
                            </div>
                            <!-- <upload-img ref="uploadChang"  :files='sceneUrls'></upload-img> -->
                            <!-- <upload-file ref="upload" :files='sceneUrls' :isFalse="true"></upload-file> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="检测负责人：">
                            {{ruleForm.userName}}
                        </el-form-item>
                        <el-form-item>
                            &nbsp;&nbsp;
                        </el-form-item>
                        <el-form-item label="检测日期：">
                            {{ruleForm.time}}
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>
            <el-form-item class="footerFixed">
                <el-button type="primary" @click="submitForm">确认无误</el-button>
                <el-button @click="showForm = 1">返回修改</el-button>
            </el-form-item>
        </div>
        <div v-show="showForm == 1">
            <div class="container" style="margin-top:20px">
                <h3 style="margin-bottom: 20px">检测</h3>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="检测机构：" prop="organization">
                        <!-- <el-input placeholder="请输入" v-model="ruleForm.organization" style="width: auto"></el-input> -->
                            <el-select v-model="ruleForm.organizations" @change="getuser" value-key="id" filterable placeholder="请选择" style="width: auto;">
                                <el-option
                                    v-for="item in detectionList"
                                    :key="item.id"
                                    :label="item.manageName"
                                    :value="item"
                                >
                                {{item.manageName}}
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <div v-if='switchHeadTab =="生产系统"'>
                            <el-form-item label="* 标准类型：" prop="standard" v-if="this.storname !='中药材' && this.storname != '辅料'">
                                <el-select v-model="standards" @change="init" disabled  filterable placeholder="请选择" style="width: 300px;">
                                    <el-option label="国标" value="1"></el-option>
                                    <el-option label='省标' value="2"></el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                        <el-form-item label="提取饮片执行标准：" v-if="storname == '提取饮片'">
                            <el-select v-model="standard" multiple collapse-tags @change="changeStandard" value-key="id" filterable placeholder="请选择" style="width: auto;">
                                <el-option
                                    v-for="item in checkList"
                                    :key="item.id"
                                    :label="item.checkName"
                                    :value="item"
                                >
                                {{item.checkName}}
                                </el-option>
                            </el-select>
                            <el-button style="margin-left:10px" @click="jianceLink">检测依据</el-button>
                        </el-form-item>
                        <el-form-item label="中药配方颗粒执行标准：" v-if="storname == '配方颗粒' && standards == '国标'">
                            <el-select v-model="standard"  collapse-tags @change="changeStandard" value-key="id" filterable placeholder="请选择" style="width: auto;">
                                <el-option
                                    v-for="item in checkList"
                                    :key="item.id"
                                    :label="item.checkName"
                                    :value="item"
                                >
                                {{item.checkName}}
                                </el-option>
                            </el-select>
                            <el-button style="margin-left:10px" @click="jianceLink">检测依据</el-button>
                        </el-form-item>
                        <el-form-item label="检测依据：" v-if="storname != '配方颗粒' && storname != '提取饮片'">
                            <el-select v-model="standard" multiple collapse-tags @change="changeStandard" value-key="id" filterable placeholder="请选择" style="width: auto;">
                                <el-option
                                    v-for="item in checkList"
                                    :key="item.id"
                                    :label="item.checkName"
                                    :value="item"
                                >
                                {{item.checkName}}
                                </el-option>
                            </el-select>
                            <el-button style="margin-left:10px" @click="jianceLink">检测依据</el-button>
                        </el-form-item>
                        <el-form-item label="检测结果：" prop="detectionResult">
                            <el-radio-group v-model="ruleForm.detectionResult">
                                <el-radio label="1" border>合格</el-radio>
                                <el-radio label="2" border>不合格</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="检测报告：" style="width:500px" v-if='switchHeadTab == "中药饮片" || (storname == "配方颗粒" && standards == "国标") || storname == "配方颗粒(颗粒)" || storname == "配方颗粒(浸膏粉)" || storname =="提取饮片" || storname =="辅料" || storname =="中药材"'>
							<!-- <upload-img ref="upload"  :files='listUrl'></upload-img> -->
                            <upload-file ref="upload" :files='listUrl' ></upload-file>
                        </el-form-item>
                        <el-form-item label="省标检测依据："  v-if='standards == "省标" && storname == "配方颗粒"' required>
                            <div class="check-container" v-for='item in provincialStandardList' :key='item.id'>
                              <div class='item'>
                                  <span class="text">省份：</span>
                                  <el-input disabled v-model="item.address"></el-input>
                              </div>
                              <div class='item'>
                                  <span class="text">标准名：</span>
                                  <el-input disabled v-model="item.checkName"></el-input>
                              </div>
                                <div class='item'>
                                    <span class="text">文件：</span>
                                    <MyUpload ref="uploadFiles" :max-num='1' @uploadRes='getUploadRes' :address='item.address' :files='listUrl' :show-tip='false'></MyUpload>
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="检测负责人：" prop="userName">
                            <el-input placeholder="请输入" v-model.trim="ruleForm.userName" style="width: auto"></el-input>
                        </el-form-item>
                        <el-form-item>
                            &nbsp;&nbsp;
                        </el-form-item>
                        <el-form-item label="报告日期：">
                            <el-date-picker type="date" placeholder="选择日期" value-format="yyyy-MM-dd" :picker-options="pickerOptions" v-model="ruleForm.time" style="width: auto;"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>
            <el-form-item class="footerFixed">
                <el-button type="primary" @click="submitRules('ruleForm')">提交</el-button>
                <el-button @click="backPage">返回</el-button>
            </el-form-item>
        </div>
        </el-form>
    </div>
</template>

<script>
import uploadFile from '../../../common/uploadfile';
import MyUpload from './components/uploadFiles.vue';
// import uploadImg from '../../../common/uploadImg';
import {
    detection_findByRelevanceId,
    check_findByAll,
    detection_save,
    detection_update,
    manage_findByAll,
    check_findByName,
    switchSystem
} from '@/request/api';
import { mapState } from 'vuex';
    export default {
        components: {
            uploadFile,
            MyUpload,
			// uploadImg,
        },
        data() {
            return {
                originProvinceStandardList:'',
                provincialStandardList:[],
				pickerOptions:{
					disabledDate(time) {
						return time.getTime() > Date.now();
					},
				},
                detectionList:'',
                showForm: 1,                                                                                                                                                                                                   keli:true,
                manufacture:{},
                standards:'1',
                standard:[],
                ruleForm: {
                    organization: '',
                    userId: '',
                    userName: '',
                    standardId: '',
                    standard: '',
                    detectionResult: '1',
                    time: '',
                    detectionUrl: '',
                    oldDetectionUrl: '',
                    standardType:''
                },
                rules: {
                    organizations: [
                        { required: true, message: '不能为空', trigger: 'blur' },
                    ],
                    detectionResult: [
                        { required: true, message: '不能为空', trigger: 'change' }
                    ],
                    userName: [
                        { required: true, message: '不能为空', trigger: 'blur' },
                    ]
                },
                listUrl: '',
                checkList: [],
                sceneUrls: [],
                materialTypeStor: '',
				time:'',
                storname:'',
                isCheck:'',
            };
        },
        computed:{
            ...mapState(['switchHeadTab'])
        },
        mounted(){
            this.getdetectionMechanism()
            var ruleForm = this.$store.state.newStorge
            this.id = this.$route.query.id
            this.isCheck = this.$route.query.isCheck
            this.storname = this.$route.query.storname
            this.type = this.$route.query.type
			this.ruleForm.standardType = this.$route.query.standard
            this.standards = this.$route.query.standard

            if(this.standards == "省标"){
                this.ruleForm.standardType   = 2
            }else if(this.standards == "国标"){
                this.ruleForm.standardType  = 1
            }


            if(this.storname == '中药材'){
                this.materialTypeStor = '中药材'
            } else if(this.storname == '辅料'){
                this.materialTypeStor = '辅料'
            } else if(this.storname == '提取饮片'){
                this.materialTypeStor = '提取饮片'
            } else if(this.storname == '配方颗粒'){
                this.materialTypeStor = '配方颗粒'
				this.keli = false
            }else if(this.storname == '配方颗粒(颗粒)'){
                this.materialTypeStor = '配方颗粒(颗粒)'
            }else if(this.storname == '配方颗粒(浸膏粉)'){
                this.materialTypeStor = '配方颗粒(浸膏粉)'
            } else if(this.storname == '中药饮片(半成品)'){
                this.materialTypeStor = '中药饮片(半成品)'
            } else if(this.storname == '中药饮片'){
                this.materialTypeStor = '中药饮片'
            }
            if (this.isCheck == '0') {
                this.init()
            } else {
                this.init1()
            }
            if (ruleForm != null) {
                if (ruleForm.detectionResult == '1') {
                    this.ruleForm = this.$store.state.newStorge
                } else if (ruleForm.detectionResult == '2'){
                    this.ruleForm = this.$store.state.newStorge
                }
            }
        },
        methods: {
            switchSystem,
            getUploadRes(res){
                const {flag,filename} = res.data
                this.provincialStandardList.forEach(item=>{
                    if(item.address == flag){
                        item.file = filename
                    }
                })

            },
            getuser(ele){

                this.ruleForm.userName = ele.userName
                this.ruleForm.organization = ele.manageName
            },
            getdetectionMechanism(){
                manage_findByAll("").then((res)=>{
                    this.detectionList = res.data
                  this.ruleForm.userName = this.detectionList[0].userName
                  this.ruleForm.organization = this.detectionList[0].manageName

                  this.ruleForm.organizations = this.detectionList[0]
                })
            },
            backPage () {
                this.$router.go(-1);
                this.$store.commit('setStorName',this.materialTypeStor)
            },
            init() {
                // 生产findbyid
                detection_findByRelevanceId({
                    id: this.id,
                    type: this.type
                }).then((res)=>{
                    this.manufacture = res.data.headMsg
                    // 检测依据
                    let data
                    if(this.storname !='中药材' && this.storname != '辅料'){
                        data = "?type="+this.materialTypeStor  + "&standard=" + this.ruleForm.standardType+'&breedName='+this.manufacture.breedName
                    }else{
                        data = "?type="+this.materialTypeStor  + "&standard=&breedName="+this.manufacture.breedName
                    }
                    if(this.switchHeadTab == '中药饮片'){
                        // data = `?type=${this.materialTypeStor}&breedName=${this.manufacture.breedName}`
                        //TODO 家龙说不传
                        data = `?type=${this.materialTypeStor}&breedName=`

                    }
                    // console.log(this.type)

                    // + "&standard=" + this.standards
                    // let data = "?" + type=""

                    // check_findByAll(data).then((res) =>{
                    //     if(res.data.length && res.data[0].checkName){
                    //         this.checkList = res.data
                    //     }
                    // })

                    check_findByName(data).then((res) =>{
                        if(this.standards == '国标' && this.type == "包装"){
                            this.checkList = res
                            this.standard = this.checkList[0]
                        }else if(this.standards == '省标' && this.type == "包装"){
                            this.checkList = res
                            let temp = JSON.parse(this.checkList[0].checkName)
                            this.checkList = temp
                            this.provincialStandardList = this.checkList
                            this.standard = this.checkList[0]
                        }else if(this.switchHeadTab == '中药饮片'){
                            this.checkList = res
                        }else if(res.length){
                            this.checkList = res
                            this.standard = this.checkList[0]
                            this.ruleForm.standard = this.checkList[0].checkName
                            this.ruleForm.standardId = this.checkList[0].id
                        }

                    }).catch(err=>{
                        throw err
                    })
                })

            },
            init1() {
                // 生产findbyid
                let data
                detection_findByRelevanceId({
                    id: this.id,
                    type: this.type
                }).then((res)=>{
                    this.manufacture = res.data.headMsg
                        if(this.switchHeadTab =='生产系统'){
                            data = "?type="+this.materialTypeStor  + "&standard=" + this.ruleForm.standardType+'&breedName='+this.manufacture.breedName
                            if(res && res.data && res.data.detection && res.data.detection.time){
                                this.time = res.data.detection.time
                            }
                            // this.ruleForm.oldDetectionUrl = this.ruleForm.detectionUrl
                            // this.ruleForm.standard = this.ruleForm.standard.split(",")
                            // this.ruleForm.standardId = this.ruleForm.standardId.split(",")

                            // this.standard
                            for(var i=0;i<this.ruleForm.standard.length;i++){
                                this.standard.push({
                                    checkName:this.ruleForm.standard[i],
                                    id:this.ruleForm.standardId[i]
                                })
                            }
                            check_findByName(data).then((res) =>{
                                if(this.standards == '国标'){
                                    this.checkList = res
                                    this.standard = this.checkList[0]
                                }else if(res.length){
                                    this.checkList = res
                                    let temp = JSON.parse(this.checkList[0].checkName)
                                    this.checkList = temp
                                    this.provincialStandardList = this.checkList
                                    this.standard = this.checkList[0]
                                }
                            }).catch(err=>{
                                throw err
                            })
                        }else{
                            // data = "?type="+this.materialTypeStor+'&breedName='+this.manufacture.breedName
                            data = "?type="+this.materialTypeStor+'&breedName='
                            if(res && res.data && res.data.detection && res.data.detection.time){
                                this.time = res.data.detection.time
                            }
                            check_findByName(data).then((res) =>{
                                if(res.length){
                                    this.checkList = res
                                }
                            }).catch(err=>{
                                throw err
                            })
                        }
                    // var arr = this.ruleForm.detectionUrl.split(",")
                    // this.listUrl = arr

                    if(this.ruleForm.detectionUrl == "" || this.ruleForm.detectionUrl == null || this.ruleForm.detectionUrl =="null"){

                    }else{
                        var arr = this.ruleForm.detectionUrl.split(",")
                        this.listUrl = arr
                        this.listUrl = arr.map(t =>{
                        var obj = {}
                        obj.url =this.$store.state.imageUrls + t
                        obj.name = this.$store.state.imageUrls + t
                        return obj
                    })
                    }

                })
               let data2 = "?type="+this.materialTypeStor  + "&standard=" + this.ruleForm.standardType
                // 检测依据
                check_findByAll(data2).then((res) =>{
                    this.checkList = res.data
                  //   this.standard.push({
                  //     checkName:this.checkList[0].checkName,
                  //     id:this.checkList[0].id
                  //   })
                  // this.ruleForm.standard = this.checkList[0].checkName
                  // this.ruleForm.standardId = this.checkList[0].id
                })
            },
            changeStandard(val) {
                // this.ruleForm.standardId = val.id
                var str = ""
                var str1 = ""
                for(var i =0;i<this.standard.length;i++){
                    str +=  this.standard[i].checkName +","
                    str1 += this.standard[i].id + ','
                }
                var strlist = str.substring(0,str.lastIndexOf(","));
                var str1list = str1.substring(0,str1.lastIndexOf(","));
                this.ruleForm.standard = strlist
                this.ruleForm.standardId = str1list
            },
            submitRules(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        // 生产场景
						// console.log(this.listUrl)
                        if(this.standards == '省标' && this.storname == '配方颗粒'){
                            this.sceneUrls = []
                            this.$refs.uploadFiles.forEach((components,index) =>{
                                // console.log(components.fileList);
                                if(components.fileList.length){
                                    this.sceneUrls.push({address:this.provincialStandardList[index].address,imageList:[...components.fileList]})
                                    this.sceneUrls.forEach(item=>{
                                        item.imageList.forEach(jack=>{
                                            var arr = jack.name.split(".")
                                            item.hz = arr[1]
                                        })
                                    })
                                }
                            })
                            if(!this.sceneUrls.length){
                                this.$message.error('请上传检测报告')
                                return
                            }
                            this.showForm = 2

                        }else{
                            this.sceneUrls = this.$refs.upload.fileList
                            for(var i=0;i<this.sceneUrls.length;i++){
                                var arr = this.sceneUrls[i].name.split(".")
                                // console.log(arr)
                                this.sceneUrls[i].hz = arr[1]
                            }
                        }

                        this.showForm = 2
                    } else {
                        return false;
                    }
                })
            },
            submitForm() {
                this.ruleForm.type = this.type
                this.ruleForm.relevanceId = this.id

                if(this.standards == '省标' && this.storname == '配方颗粒'){
                    var arr=""
                    var formdata = new FormData()
                    this.$refs.uploadFiles.forEach(components=>{
                        var imgurls = components.fileList
                        for(var i=0;i<imgurls.length;i++){
                            if(imgurls[i].status != "success"){
                                formdata.append("files",imgurls[i].raw)
                            }
                            arr += imgurls[i].name + ','
                        }
                    })

                    const detectionUrl = arr.substr(0,arr.length-1)
                    this.ruleForm.detectionUrl = detectionUrl.substring(detectionUrl.lastIndexOf("/")+1)
                    let temp = JSON.stringify(this.provincialStandardList)
                    this.ruleForm.info = temp
                    this.ruleForm.materialType = this.storname
                    for(var a in this.ruleForm){
                        formdata.append(a,this.ruleForm[a])
                    }
                    detection_save(formdata).then((res) => {
                        this.$notify({
                            title: '提示',
                            message: '添加成功',
                            type: 'success',
                            duration:1000
                        });
                        this.backPage()
                    })
                }else{
                    var imgurls = this.$refs.upload.fileList
                    var formdata = new FormData()
                    var arr=""
                    for(var i=0;i<imgurls.length;i++){
                        if(imgurls[i].status != "success"){
                            formdata.append("files",imgurls[i].raw)
                        }
                        arr += imgurls[i].name + ','
                    }
                    const detectionUrl = arr.substr(0,arr.length-1)
                    this.ruleForm.detectionUrl = detectionUrl.substring(detectionUrl.lastIndexOf("/")+1)
                    for(var a in this.ruleForm){
                        formdata.append(a,this.ruleForm[a])
                    }
                    // if (this.isCheck == '0') {
                    detection_save(formdata).then((res) => {
                        this.$notify({
                            title: '提示',
                            message: '添加成功',
                            type: 'success',
                            duration:1000
                        });
                        this.backPage()
                    })
                }

                // } else {
                //     detection_update(formdata).then((res) => {
                //         this.$notify({
                //             title: '提示',
                //             message: '修改成功',
                //             type: 'success',
                //             duration:1000
                //         });
                //         this.backPage()
                //     })
                // }
            },
            jianceLink() {
                var data = this.$store.getters.permission
                var items = ""
                for (let i = 0; i < data.length; i++) {
                    if(data[i].name == "检测依据"){
                     items = 1
                    }
                }
                if (items == "1"){
                    this.$router.push({
                        path:'/checkingBasis/added'
                    })
                    this.$store.commit('setStorge',this.ruleForm)
                }else{
                    this.$router.push({
                        path:'/403'
                    })
                }
            }
        }
    }
</script>
<style scoped lang="less">
.image-list{
    display: flex;
    //background-color: rgba(246, 245, 245, 0.44);
    padding: 20px;
    width: 100%;
    box-shadow: 0 0 5px 2px rgba(220, 220, 220, 0.44);
    margin-bottom: 20px;
    .location{
        width: 120px;
        .item{
            margin-right: 10px;
        }
    }
}
.check-container{
    display: flex;
    align-content: center;
    width: 1000px;
    margin-bottom: 30px;
    .text{
        width: 72px;
    }
    .item{
        display: flex;
        margin-right: 30px;
    }
}
.el-date-editor.el-input{
    width: 200px !important
}
.el-select{
    width: 200px !important
}
</style>
